package com.zhl.factory;

import com.zhl.entity.User;
import com.zhl.service.UserService;
import com.zhl.utils.TransactionManager;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * 工厂类
 */
public class BeanFactory {
    //针对业务层  UserService 代理
    private UserService userService; //真实角色

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
    //针对业务层的真实角色--- 使用事务
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
    public UserService getUserService(){
        return (UserService) Proxy.newProxyInstance(
                userService.getClass().getClassLoader(),
                userService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object obj = null;
                        try {
                            //开启事务
                            transactionManager.benginTransaction();
                            //执行业务操作
                            obj =  method.invoke(userService,args);
                            //提交事务
                            transactionManager.commit();
                            return obj;
                        } catch (Exception e) {
                            //事务回滚
                            transactionManager.rollback();
                            throw new RuntimeException(e);
                        }finally {
                            //释放资源
                            transactionManager.close();
                        }


                    }
                }
        );
    }
}














